#include <unistd.h>
#include "test.h"

int main()
{
    while (1) {
        say_hello();
        sleep(1);
    }
    return 0;
}

#if 0
gcc main.c -L. -ltest -o main
export LD_LIBRARY_PATH=`pwd`:$LD_LIBRARY_PATH

./main 
hello.


1.尝试 hook libtest.so中say_hello() 调用的 malloc()函数，替换成自己的my_malloc()函数.

    查询被hook函数的.got.plt表项地址

    readelf -r libtest.so

        Relocation section '.rela.dyn' at offset 0x4a8 contains 7 entries:
          Offset          Info           Type           Sym. Value    Sym. Name + Addend
        000000003e10  000000000008 R_X86_64_RELATIVE                    1150
        000000003e18  000000000008 R_X86_64_RELATIVE                    1110
        000000004030  000000000008 R_X86_64_RELATIVE                    4030
        000000003fe0  000100000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_deregisterTMClone + 0
        000000003fe8  000400000006 R_X86_64_GLOB_DAT 0000000000000000 __gmon_start__ + 0
        000000003ff0  000600000006 R_X86_64_GLOB_DAT 0000000000000000 _ITM_registerTMCloneTa + 0
        000000003ff8  000700000006 R_X86_64_GLOB_DAT 0000000000000000 __cxa_finalize@GLIBC_2.2.5 + 0

        Relocation section '.rela.plt' at offset 0x550 contains 3 entries:
          Offset          Info           Type           Sym. Value    Sym. Name + Addend
        000000004018  000200000007 R_X86_64_JUMP_SLO 0000000000000000 printf@GLIBC_2.2.5 + 0
        000000004020  000300000007 R_X86_64_JUMP_SLO 0000000000000000 snprintf@GLIBC_2.2.5 + 0
        000000004028  000500000007 R_X86_64_JUMP_SLO 0000000000000000 malloc@GLIBC_2.2.5 + 0

        可以看到malloc()函数的.got.plt表项地址为 0x000000004028 。

        当然这个地址是相对地址，实际地址还需要加上libtest.so在进程空间 vma 中的基地址。

        VMA 表示虚拟地址，LMA 表示加载地址

    ./main &
    ps -ef | grep main
    
        377097 pts/4    00:00:00 main

    cat /proc/377097/maps
        7f52b143a000-7f52b143b000 r--p 00000000 08:01 1459024                    /home/share/work/ac-code/reverse/attack/injection/hook-so/libtest.so
        7f52b143b000-7f52b143c000 r-xp 00001000 08:01 1459024                    /home/share/work/ac-code/reverse/attack/injection/hook-so/libtest.so
        7f52b143c000-7f52b143d000 r--p 00002000 08:01 1459024                    /home/share/work/ac-code/reverse/attack/injection/hook-so/libtest.so
        7f52b143d000-7f52b143e000 r--p 00002000 08:01 1459024                    /home/share/work/ac-code/reverse/attack/injection/hook-so/libtest.so
        7f52b143e000-7f52b143f000 rw-p 00003000 08:01 1459024                    /home/share/work/ac-code/reverse/attack/injection/hook-so/libtest.so

        libtest.so的基地址为 0x7f52b143a000 。
        接下来我们修改 0x000000004028 + 0x7f52b143a000 地址中的内容，就可以 hook libtest.so 中的 malloc 函数了。

    hook-so.c

#endif
